"""
通用工具函数模块
"""
import datetime
import hashlib
import json
import logging
import os
import random
import re
import time
from urllib.parse import urlparse

logger = logging.getLogger(__name__)


def get_timestamp():
    """获取当前时间戳"""
    return int(time.time())


def get_formatted_time(format_str="%Y-%m-%d %H:%M:%S"):
    """获取格式化的时间字符串"""
    return datetime.datetime.now().strftime(format_str)


def md5(text):
    """计算文本的MD5值"""
    if isinstance(text, str):
        text = text.encode('utf-8')
    return hashlib.md5(text).hexdigest()


def get_domain(url):
    """从URL中提取域名"""
    parsed_uri = urlparse(url)
    return parsed_uri.netloc


def save_json(data, filepath):
    """保存数据为JSON文件"""
    with open(filepath, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    logger.info(f"数据已保存到: {filepath}")


def load_json(filepath):
    """从JSON文件加载数据"""
    with open(filepath, 'r', encoding='utf-8') as f:
        return json.load(f) 